Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.

  • Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [1]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("data/lfw/*/*"))
dog_files = np.array(glob("data/dog_images/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 13233 total human images.
There are 8351 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [2]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [3]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

  • Humans detected correctly: 96.00%
  • Dogs detected as humans: 18.00%
In [4]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
humans = []
dogs = []
for human, dog in tqdm(zip(human_files_short, dog_files_short)):
    humans.append(face_detector(human))
    dogs.append(face_detector(dog))
    
print(f'Humans detected correctly: {np.sum(humans)/len(humans):.2%}')
print(f'Dogs detected as humans: {np.sum(dogs)/len(dogs):.2%}')
100it [00:08, 11.90it/s]
Humans detected correctly: 96.00%
Dogs detected as humans: 18.00%
In [5]:
def show_images(images, cols = 4, titles = None):
    """Display a list of images in a single figure with matplotlib.
    
    Parameters
    ---------
    images: List of np.arrays compatible with plt.imshow.
    
    cols (Default = 1): Number of columns in figure (number of rows is 
                        set to np.ceil(n_images/float(cols))).
    
    titles: List of titles corresponding to each image. Must have
            the same length as titles.
    """
    assert((titles is None) or (len(images) == len(titles)))
    n_images = len(images)
    if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
    fig = plt.figure()
    for n, (image, title) in enumerate(zip(images, titles)):
        #a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
        a = fig.add_subplot(np.ceil(n_images/float(cols)), cols, n + 1)
        #if image.ndim == 2:
        #    plt.gray()
        plt.imshow(image, interpolation='nearest')
        plt.axis('off')
        a.set_title(title)
    fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
    plt.show()

Pictures of humans with no faces detected

In [6]:
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

humans = np.array(humans)
images = [Image.open(human_files_short[i]) for i in np.where(~humans)[0]]
titles = [human_files_short[i].split('/')[-1] for i in np.where(~humans)[0]]
show_images(images, titles=titles)

Pictures of dogs where faces were detected

In [7]:
dogs = np.array(dogs)
images = [Image.open(dog_files_short[i]) for i in np.flatnonzero(dogs)]
titles = [dog_files_short[i].split('/')[-1] for i in np.flatnonzero(dogs)]
show_images(images, titles=titles)

As we can see in the pictures above the face detector makes some mistakes on the dog pictures but it also correctly finds human faces inside some pictures from the dogs folder.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [8]:
### (Optional) 
### TODO: Test performance of another face detection algorithm.
### Feel free to use as many code cells as needed.

### https://github.com/ageitgey/face_recognition
import face_recognition

def face_detector_opt(img_path):
    image = face_recognition.load_image_file(img_path)
    faces = face_recognition.face_locations(image)

    return len(faces) > 0

humans = []
dogs = []
for human, dog in tqdm(zip(human_files_short, dog_files_short)):
    humans.append(face_detector_opt(human))
    dogs.append(face_detector_opt(dog))
    
print(f'Humans detected correctly: {np.sum(humans)/len(humans):.2%}')
print(f'Dogs detected as humans: {np.sum(dogs)/len(dogs):.2%}')
100it [00:25,  3.90it/s]
Humans detected correctly: 99.00%
Dogs detected as humans: 13.00%

Pictures of humans with no faces detected by the optional algorithm

In [9]:
humans = np.array(humans)
images = [Image.open(human_files_short[i]) for i in np.where(~humans)[0]]
titles = [human_files_short[i].split('/')[-1] for i in np.where(~humans)[0]]
show_images(images, titles=titles)

Pictures of humans with no faces detected by the optional algorithm

In [10]:
dogs = np.array(dogs)
images = [Image.open(dog_files_short[i]) for i in np.flatnonzero(dogs)]
titles = [dog_files_short[i].split('/')[-1] for i in np.flatnonzero(dogs)]
show_images(images, titles=titles)

As we can see from the results above the face_recognition package based on http://dlib.net/ does fewer mistakes


Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [11]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    VGG16 = VGG16.cuda()

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

In [12]:
from PIL import Image
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision

def VGG16_predict(img_path):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    img = Image.open(img_path)
    min_img_size = 224
    transform_pipeline = transforms.Compose([transforms.Resize((min_img_size, min_img_size)),
                                             transforms.ToTensor(),
                                             transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                                  std=[0.229, 0.224, 0.225])])
    
    img = transform_pipeline(img)
    img = img.unsqueeze(0)
    
    if use_cuda:
        img = img.to('cuda')
    
    prediction = VGG16(img)
    prediction = prediction.argmax()
    
    return prediction # predicted class index

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [13]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    prediction_index = VGG16_predict(img_path).data.cpu().numpy()
    is_dog = 151 <= prediction_index <= 268
    return is_dog  # true/false

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

  • Humans detected as dogs: 0.00%
  • Dogs detected correctly: 94.00%
In [14]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

humans = []
dogs = []
for human, dog in zip(human_files_short, dog_files_short):
    humans.append(dog_detector(human))
    dogs.append(dog_detector(dog))
    
print(f'Humans detected as dogs: {np.sum(humans)/len(humans):.2%}')
print(f'Dogs detected correctly: {np.sum(dogs)/len(dogs):.2%}')
Humans detected as dogs: 0.00%
Dogs detected correctly: 94.00%

Dogs not detected correctly

In [15]:
dogs = np.array(dogs)
images = [Image.open(dog_files_short[i]) for i in np.where(~dogs)[0]]
titles = [human_files_short[i].split('/')[-1] for i in np.where(~dogs)[0]]
show_images(images, titles=titles)

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [16]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.

# define AlexNet model
alex_net = models.alexnet(pretrained=True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda:
    alex_net = alex_net.cuda()
In [17]:
def alex_net_predict(img_path):
    '''
    Use pre-trained AlexNet model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to AlexNet model's prediction
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    img = Image.open(img_path)
    min_img_size = 224
    transform_pipeline = transforms.Compose([transforms.Resize((min_img_size, min_img_size)),
                                             transforms.ToTensor(),
                                             transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                                                  std=[0.229, 0.224, 0.225])])
    
    img = transform_pipeline(img)
    img = img.unsqueeze(0)
    
    if use_cuda:
        img = img.to('cuda')
    
    prediction = alex_net(img)
    prediction = prediction.argmax()
    
    return prediction # predicted class index
In [18]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector_alex_net(img_path):
    ## TODO: Complete the function.
    prediction_index = alex_net_predict(img_path).data.cpu().numpy()
    is_dog = 151 <= prediction_index <= 268
    return is_dog  # true/false
In [19]:
### Test the performance of the dog_detector_alex_net function
### on the images in human_files_short and dog_files_short.

humans = []
dogs = []
for human, dog in zip(human_files_short, dog_files_short):
    humans.append(dog_detector_alex_net(human))
    dogs.append(dog_detector_alex_net(dog))
    
print(f'Humans detected as dogs: {np.sum(humans)/len(humans):.2%}')
print(f'Dogs detected correctly: {np.sum(dogs)/len(dogs):.2%}')
Humans detected as dogs: 1.00%
Dogs detected correctly: 93.00%

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [20]:
import os
from torchvision import datasets

### TODO: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
data_dir = 'data/dog_images'
TRAIN = 'train'
VAL = 'valid'
TEST = 'test'

means = [0.485, 0.456, 0.406]
stds = [0.229, 0.224, 0.225]
input_shape = 224
batch_size = 32
scale = 256

data_transforms = {
    TRAIN: transforms.Compose([
        # Data augmentation is a good practice for the train set
        # Here, we randomly crop the image to 224x224 and
        # randomly flip it horizontally. 
        transforms.RandomRotation(degrees=30),
        transforms.RandomResizedCrop(input_shape),
        transforms.RandomVerticalFlip(p=0.3),
        transforms.RandomHorizontalFlip(p=0.4),
        transforms.ToTensor(),
        transforms.Normalize(means, stds)
    ]),
    VAL: transforms.Compose([
        transforms.Resize(scale),
        transforms.CenterCrop(input_shape),
        transforms.ToTensor(),
        transforms.Normalize(means, stds)
    ]),
    TEST: transforms.Compose([
        transforms.Resize(scale),
        transforms.CenterCrop(input_shape),
        transforms.ToTensor(),
        transforms.Normalize(means, stds)
    ])
}

image_datasets = {
    x: datasets.ImageFolder(
        os.path.join(data_dir, x), 
        transform=data_transforms[x]
    )
    for x in [TRAIN, VAL, TEST]
}

loaders_scratch = {
    x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size,shuffle=True, num_workers=0)
    for x in [TRAIN, VAL, TEST]
}

dataset_sizes = {x: len(image_datasets[x]) for x in [TRAIN, VAL, TEST]}

for x in [TRAIN, VAL, TEST]:
    print("Loaded {} images under {}".format(dataset_sizes[x], x))
    
print("Classes: ")
class_names = image_datasets[TRAIN].classes
print(image_datasets[TRAIN].classes)
Loaded 6680 images under train
Loaded 835 images under valid
Loaded 836 images under test
Classes: 
['001.Affenpinscher', '002.Afghan_hound', '003.Airedale_terrier', '004.Akita', '005.Alaskan_malamute', '006.American_eskimo_dog', '007.American_foxhound', '008.American_staffordshire_terrier', '009.American_water_spaniel', '010.Anatolian_shepherd_dog', '011.Australian_cattle_dog', '012.Australian_shepherd', '013.Australian_terrier', '014.Basenji', '015.Basset_hound', '016.Beagle', '017.Bearded_collie', '018.Beauceron', '019.Bedlington_terrier', '020.Belgian_malinois', '021.Belgian_sheepdog', '022.Belgian_tervuren', '023.Bernese_mountain_dog', '024.Bichon_frise', '025.Black_and_tan_coonhound', '026.Black_russian_terrier', '027.Bloodhound', '028.Bluetick_coonhound', '029.Border_collie', '030.Border_terrier', '031.Borzoi', '032.Boston_terrier', '033.Bouvier_des_flandres', '034.Boxer', '035.Boykin_spaniel', '036.Briard', '037.Brittany', '038.Brussels_griffon', '039.Bull_terrier', '040.Bulldog', '041.Bullmastiff', '042.Cairn_terrier', '043.Canaan_dog', '044.Cane_corso', '045.Cardigan_welsh_corgi', '046.Cavalier_king_charles_spaniel', '047.Chesapeake_bay_retriever', '048.Chihuahua', '049.Chinese_crested', '050.Chinese_shar-pei', '051.Chow_chow', '052.Clumber_spaniel', '053.Cocker_spaniel', '054.Collie', '055.Curly-coated_retriever', '056.Dachshund', '057.Dalmatian', '058.Dandie_dinmont_terrier', '059.Doberman_pinscher', '060.Dogue_de_bordeaux', '061.English_cocker_spaniel', '062.English_setter', '063.English_springer_spaniel', '064.English_toy_spaniel', '065.Entlebucher_mountain_dog', '066.Field_spaniel', '067.Finnish_spitz', '068.Flat-coated_retriever', '069.French_bulldog', '070.German_pinscher', '071.German_shepherd_dog', '072.German_shorthaired_pointer', '073.German_wirehaired_pointer', '074.Giant_schnauzer', '075.Glen_of_imaal_terrier', '076.Golden_retriever', '077.Gordon_setter', '078.Great_dane', '079.Great_pyrenees', '080.Greater_swiss_mountain_dog', '081.Greyhound', '082.Havanese', '083.Ibizan_hound', '084.Icelandic_sheepdog', '085.Irish_red_and_white_setter', '086.Irish_setter', '087.Irish_terrier', '088.Irish_water_spaniel', '089.Irish_wolfhound', '090.Italian_greyhound', '091.Japanese_chin', '092.Keeshond', '093.Kerry_blue_terrier', '094.Komondor', '095.Kuvasz', '096.Labrador_retriever', '097.Lakeland_terrier', '098.Leonberger', '099.Lhasa_apso', '100.Lowchen', '101.Maltese', '102.Manchester_terrier', '103.Mastiff', '104.Miniature_schnauzer', '105.Neapolitan_mastiff', '106.Newfoundland', '107.Norfolk_terrier', '108.Norwegian_buhund', '109.Norwegian_elkhound', '110.Norwegian_lundehund', '111.Norwich_terrier', '112.Nova_scotia_duck_tolling_retriever', '113.Old_english_sheepdog', '114.Otterhound', '115.Papillon', '116.Parson_russell_terrier', '117.Pekingese', '118.Pembroke_welsh_corgi', '119.Petit_basset_griffon_vendeen', '120.Pharaoh_hound', '121.Plott', '122.Pointer', '123.Pomeranian', '124.Poodle', '125.Portuguese_water_dog', '126.Saint_bernard', '127.Silky_terrier', '128.Smooth_fox_terrier', '129.Tibetan_mastiff', '130.Welsh_springer_spaniel', '131.Wirehaired_pointing_griffon', '132.Xoloitzcuintli', '133.Yorkshire_terrier']

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:

  • The images are resized by doing a crop of random size (from 0.08 to 1.0) of the original size and a random aspect ratio (of 3/4 to 4/3) of the original aspect ratio. This crop is finally resized to 224x224 pixels in order to be able to reuse the same data loaders for the transfer learning step.
  • The dataset is augmented by using a random rotation of 30 degrees, a random vertical flip with 0.3 probability and a random horizontal flip with 0.4 probability

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [22]:
import torch.nn as nn
import torch.nn.functional as F

# define the CNN architecture
class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self):
        super(Net, self).__init__()
        ## Define layers of a CNN
        self.features = nn.Sequential(
            # 1st 2D convolution layer
            nn.Conv2d(3, 16, kernel_size=2, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            
            # Defining another 2D convolution layer
            nn.Conv2d(16, 32, kernel_size=2, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            
            # Defining another 2D convolution layer
            nn.Conv2d(32, 64, kernel_size=2, stride=1, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=2, stride=2),
            
            nn.Dropout(p=0.5),
            nn.AvgPool2d(kernel_size=2, stride=2)
        )
        
        self.classifier = nn.Sequential(
            nn.Linear(64 * 14 * 14, 133),
            nn.LogSoftmax(dim=1)
        )
    
    def forward(self, x):
        ## Define forward behavior
        out = self.features(x)
        out = out.view(-1, 64*14*14)
        out = self.classifier(out)
        
        return out

#-#-# You so NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()

# move tensors to GPU if CUDA is available
if use_cuda:
    model_scratch.cuda()

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

  • The architecture is composed from a feature extractor and a classifier
  • The feature extractor is has 3 CNN layers in to extract features. Each CNN layer has a ReLU activation and a 2D max pooling layer in to reduce the amount of parameters and computation in the network
  • After the CNN layers we have a dropout layer with a probability of 0.5 in to prevent overfitting and an average pooling layer to calculate the average for each patch of the feature map
  • The classifier is a fully connected layer with an input shape of 64 x 14 x 14 (which matches the output from the average pooling layer) and 133 nodes, one for each class (there are 133 dog breeds). We add a softmax activation to get the probabilities for each class

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [23]:
import torch.optim as optim

### TODO: select loss function
criterion_scratch = nn.CrossEntropyLoss()

### TODO: select optimizer
optimizer_scratch = torch.optim.Adam(model_scratch.parameters())

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [24]:
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    valid_loss_min = np.Inf 
    
    for epoch in range(1, n_epochs+1):
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## find the loss and update the model parameters accordingly
            ## record the average training loss, using something like
            ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            
            #Set the parameter gradients to zero
            optimizer.zero_grad()
            
            #Forward pass, backward pass, optimize
            outputs = model(data)
            loss = criterion(outputs, target)
            loss.backward()
            optimizer.step()
            
            train_loss += ((1 / (batch_idx + 1)) * (loss.data - train_loss))
            
        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda:
                data, target = data.cuda(), target.cuda()
            ## update the average validation loss
            val_outputs = model(data)
            val_loss = criterion(val_outputs, target)
            valid_loss += ((1 / (batch_idx + 1)) * (val_loss.data - valid_loss))

            
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
            epoch, 
            train_loss,
            valid_loss
            ))
        
        ## TODO: save the model if validation loss has decreased
        if(valid_loss < valid_loss_min):
            print('Saving model: Validation Loss: {:.6f} decreased \tOld Validation Loss: {:.6f}'.format(valid_loss, valid_loss_min))
            valid_loss_min = valid_loss
            torch.save(model.state_dict(), save_path)
            
    # return trained model
    return model


# train the model
model_scratch = train(50, loaders_scratch, model_scratch, optimizer_scratch, criterion_scratch, use_cuda, 'model_scratch.pt')

# load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
Epoch: 1 	Training Loss: 4.800115 	Validation Loss: 4.577640
Saving model: Validation Loss: 4.577640 decreased 	Old Validation Loss: inf
Epoch: 2 	Training Loss: 4.596466 	Validation Loss: 4.466234
Saving model: Validation Loss: 4.466234 decreased 	Old Validation Loss: 4.577640
Epoch: 3 	Training Loss: 4.524200 	Validation Loss: 4.410961
Saving model: Validation Loss: 4.410961 decreased 	Old Validation Loss: 4.466234
Epoch: 4 	Training Loss: 4.465098 	Validation Loss: 4.335465
Saving model: Validation Loss: 4.335465 decreased 	Old Validation Loss: 4.410961
Epoch: 5 	Training Loss: 4.397717 	Validation Loss: 4.303605
Saving model: Validation Loss: 4.303605 decreased 	Old Validation Loss: 4.335465
Epoch: 6 	Training Loss: 4.352687 	Validation Loss: 4.272016
Saving model: Validation Loss: 4.272016 decreased 	Old Validation Loss: 4.303605
Epoch: 7 	Training Loss: 4.293440 	Validation Loss: 4.272441
Epoch: 8 	Training Loss: 4.252130 	Validation Loss: 4.189270
Saving model: Validation Loss: 4.189270 decreased 	Old Validation Loss: 4.272016
Epoch: 9 	Training Loss: 4.205837 	Validation Loss: 4.176158
Saving model: Validation Loss: 4.176158 decreased 	Old Validation Loss: 4.189270
Epoch: 10 	Training Loss: 4.162156 	Validation Loss: 4.153286
Saving model: Validation Loss: 4.153286 decreased 	Old Validation Loss: 4.176158
Epoch: 11 	Training Loss: 4.115100 	Validation Loss: 4.223742
Epoch: 12 	Training Loss: 4.106990 	Validation Loss: 4.149275
Saving model: Validation Loss: 4.149275 decreased 	Old Validation Loss: 4.153286
Epoch: 13 	Training Loss: 4.077336 	Validation Loss: 4.145404
Saving model: Validation Loss: 4.145404 decreased 	Old Validation Loss: 4.149275
Epoch: 14 	Training Loss: 4.045778 	Validation Loss: 4.124165
Saving model: Validation Loss: 4.124165 decreased 	Old Validation Loss: 4.145404
Epoch: 15 	Training Loss: 4.025392 	Validation Loss: 4.167387
Epoch: 16 	Training Loss: 3.990855 	Validation Loss: 4.004549
Saving model: Validation Loss: 4.004549 decreased 	Old Validation Loss: 4.124165
Epoch: 17 	Training Loss: 3.963948 	Validation Loss: 4.062632
Epoch: 18 	Training Loss: 3.932757 	Validation Loss: 4.008663
Epoch: 19 	Training Loss: 3.907443 	Validation Loss: 4.019051
Epoch: 20 	Training Loss: 3.880832 	Validation Loss: 4.065052
Epoch: 21 	Training Loss: 3.885328 	Validation Loss: 4.052078
Epoch: 22 	Training Loss: 3.857102 	Validation Loss: 3.951113
Saving model: Validation Loss: 3.951113 decreased 	Old Validation Loss: 4.004549
Epoch: 23 	Training Loss: 3.824729 	Validation Loss: 3.997753
Epoch: 24 	Training Loss: 3.805030 	Validation Loss: 4.006763
Epoch: 25 	Training Loss: 3.796946 	Validation Loss: 4.038730
Epoch: 26 	Training Loss: 3.790872 	Validation Loss: 3.924551
Saving model: Validation Loss: 3.924551 decreased 	Old Validation Loss: 3.951113
Epoch: 27 	Training Loss: 3.780535 	Validation Loss: 3.909545
Saving model: Validation Loss: 3.909545 decreased 	Old Validation Loss: 3.924551
Epoch: 28 	Training Loss: 3.759525 	Validation Loss: 3.933406
Epoch: 29 	Training Loss: 3.753687 	Validation Loss: 3.936720
Epoch: 30 	Training Loss: 3.718647 	Validation Loss: 3.928680
Epoch: 31 	Training Loss: 3.685244 	Validation Loss: 3.929645
Epoch: 32 	Training Loss: 3.675629 	Validation Loss: 3.976343
Epoch: 33 	Training Loss: 3.670979 	Validation Loss: 3.900103
Saving model: Validation Loss: 3.900103 decreased 	Old Validation Loss: 3.909545
Epoch: 34 	Training Loss: 3.667839 	Validation Loss: 3.951787
Epoch: 35 	Training Loss: 3.646753 	Validation Loss: 3.883459
Saving model: Validation Loss: 3.883459 decreased 	Old Validation Loss: 3.900103
Epoch: 36 	Training Loss: 3.612391 	Validation Loss: 3.862474
Saving model: Validation Loss: 3.862474 decreased 	Old Validation Loss: 3.883459
Epoch: 37 	Training Loss: 3.631999 	Validation Loss: 4.073159
Epoch: 38 	Training Loss: 3.610629 	Validation Loss: 3.816751
Saving model: Validation Loss: 3.816751 decreased 	Old Validation Loss: 3.862474
Epoch: 39 	Training Loss: 3.596606 	Validation Loss: 3.903385
Epoch: 40 	Training Loss: 3.564602 	Validation Loss: 3.984472
Epoch: 41 	Training Loss: 3.552500 	Validation Loss: 3.854142
Epoch: 42 	Training Loss: 3.584418 	Validation Loss: 3.892016
Epoch: 43 	Training Loss: 3.560993 	Validation Loss: 3.865376
Epoch: 44 	Training Loss: 3.559407 	Validation Loss: 3.906562
Epoch: 45 	Training Loss: 3.546641 	Validation Loss: 3.896481
Epoch: 46 	Training Loss: 3.553527 	Validation Loss: 3.903724
Epoch: 47 	Training Loss: 3.499455 	Validation Loss: 3.893786
Epoch: 48 	Training Loss: 3.503983 	Validation Loss: 3.806589
Saving model: Validation Loss: 3.806589 decreased 	Old Validation Loss: 3.816751
Epoch: 49 	Training Loss: 3.498622 	Validation Loss: 3.951965
Epoch: 50 	Training Loss: 3.481745 	Validation Loss: 3.829610
Out[24]:
<All keys matched successfully>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [25]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda:
            data, target = data.cuda(), target.cuda()
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        # calculate the loss
        loss = criterion(output, target)
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
        100. * correct / total, correct, total))

# call test function    
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
Test Loss: 3.701185


Test Accuracy: 17% (146/836)

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [30]:
## TODO: Specify data loaders

# Same as above
loaders_transfer = loaders_scratch

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [26]:
import torchvision.models as models
import torch.nn as nn

## TODO: Specify model architecture 
model_transfer = models.vgg16(pretrained=True)

# Freeze parameters so we don't backprop through them
for param in model_transfer.parameters():
    param.requires_grad = False

classifier = nn.Sequential(
    nn.Linear(25088, 1024),
    nn.ReLU(inplace=True),
    nn.Dropout(p=0.4),
    nn.Linear(1024, 133),
    nn.LogSoftmax(dim=1)
)

model_transfer.classifier = classifier    
    
if use_cuda:
    model_transfer = model_transfer.cuda()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

  • We use the VGG16 network that was pretrained on the ImageNet dataset. The ImageNet dataset containes similar images with our own dataset so we can keep the feature extractor part.
  • Because we have a small dataset and we don't need to identify dogs but dog breeds we replace the classifier with a fully connected layer with 1024 nodes, with ReLU and a dropout with a 0.4 probability, connected to an output layer with 133 nodes (same as the number of classes)
  • We then train the model but we freeze the parameters for the feature extractor so only the classifier paramters get backpropagated

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [28]:
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = torch.optim.Adam(model_transfer.classifier.parameters())

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [31]:
# train the model
model_transfer = train(10, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')

# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
Epoch: 1 	Training Loss: 4.022158 	Validation Loss: 1.643293
Saving model: Validation Loss: 1.643293 decreased 	Old Validation Loss: inf
Epoch: 2 	Training Loss: 2.877581 	Validation Loss: 1.419630
Saving model: Validation Loss: 1.419630 decreased 	Old Validation Loss: 1.643293
Epoch: 3 	Training Loss: 2.626851 	Validation Loss: 1.224912
Saving model: Validation Loss: 1.224912 decreased 	Old Validation Loss: 1.419630
Epoch: 4 	Training Loss: 2.551781 	Validation Loss: 1.134145
Saving model: Validation Loss: 1.134145 decreased 	Old Validation Loss: 1.224912
Epoch: 5 	Training Loss: 2.533542 	Validation Loss: 1.059724
Saving model: Validation Loss: 1.059724 decreased 	Old Validation Loss: 1.134145
Epoch: 6 	Training Loss: 2.511676 	Validation Loss: 1.126237
Epoch: 7 	Training Loss: 2.487848 	Validation Loss: 1.109611
Epoch: 8 	Training Loss: 2.466784 	Validation Loss: 1.129371
Epoch: 9 	Training Loss: 2.443431 	Validation Loss: 1.102462
Epoch: 10 	Training Loss: 2.431815 	Validation Loss: 1.081638
Out[31]:
<All keys matched successfully>

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [32]:
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
Test Loss: 1.142807


Test Accuracy: 68% (576/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [33]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

# list of class names by index, i.e. a name can be accessed like class_names[0]
class_names = [item[4:].replace("_", " ") for item in image_datasets['train'].classes]

def process_image(image):
    ''' Scales, crops, and normalizes a PIL image for a PyTorch model,
        returns an Numpy array
    '''
    
    # scale
    scale_size = 256,256
    image.thumbnail(scale_size, Image.LANCZOS)

    # crop
    crop_size = 224
    width, height = image.size   # Get dimensions
    
    left = (width - crop_size)/2
    top = (height - crop_size)/2
    right = (width + crop_size)/2
    bottom = (height + crop_size)/2
    
    image = image.crop((left, top, right, bottom))
    
    # normalize
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    image_array = np.array(image) / 255
    
    image = (image_array - mean) / std
    
    # reorder dimensions
    image = image.transpose((2,0,1))
    
    return torch.from_numpy(image)

def predict_breed_transfer(img_path):
    # load the image and return the predicted breed
        # open image
    image = Image.open(img_path)
    image = process_image(image)
    image = image.unsqueeze_(0)
    if use_cuda:
        image = image.cuda().float()
    
    model_transfer.eval()
    
    with torch.no_grad():
        output = model_transfer(image)
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
    
    return class_names[pred]

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [34]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def run_app(img_path):
    ## handle cases for a human face, dog, and neither
    is_dog = False
    if dog_detector(img_path):
        is_dog = True
        title = 'Nice doggie!'
    elif face_detector(img_path):
        title = "Hello, hooooman!"
    else:
        title = "Hello, thing!"
        
    
    breed = predict_breed_transfer(img_path)
    
    if is_dog:
        sub_title = f'You are a {breed}, aren\'t you?!?'
    else:
        sub_title = f'You look like a...{breed}. Hmm, weird!!!'
        
    image = Image.open(img_path)
    plt.imshow(image, interpolation='nearest')
    plt.axis('off')
    plt.title(f'{title}\n{sub_title}')
    plt.show()
    plt.close()

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: (Three possible points for improvement)

Possible improvements:

  1. Show the image of the look-a-like class next to the prediction
  2. Detect if in the picture are both humans and dogs and show predictions or look-a-likes for both
  3. Detect multiple breeds from the same picture
  4. Detect metis dogs and show the two most close breeds
In [35]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
images = [
    'images/test/cat_1.jpg',
    'images/test/dalmatian.jpeg',
    'images/test/snoop.jpg',
    'images/test/german_shepherd.jpg',
    'images/test/cat_2.jpg',
    'images/test/raduenuca.jpg'
]
for file in images:
    run_app(file)